const esbuild = require('esbuild');
const path = require('path');

const isWatch = process.argv.includes('--watch');
const isDev = process.argv.includes('--dev');

const buildOptions = {
  entryPoints: ['src/index.tsx'],
  bundle: true,
  platform: 'node',
  target: 'node16',
  outfile: 'dist/index.js',
  format: 'esm',
  external: [
    'react', 
    'ink',
    'lowlight',
    'ansi-escapes',
    'axios',
    'string-width',
    'strip-ansi'
  ],
  minify: !isDev,
  sourcemap: isDev,
  define: {
    'process.env.NODE_ENV': isDev ? '"development"' : '"production"'
  },
  banner: {
    js: '#!/usr/bin/env node\n'
  },
  logLevel: 'info'
};

async function build() {
  try {
    if (isWatch) {
      const context = await esbuild.context(buildOptions);
      await context.watch();
      console.log('👀 监听文件变化中...');
    } else {
      await esbuild.build(buildOptions);
      console.log('✅ 构建完成!');
      
      // 设置执行权限
      const fs = require('fs');
      const outputPath = path.resolve('dist/index.js');
      if (fs.existsSync(outputPath)) {
        fs.chmodSync(outputPath, '755');
        console.log('✅ 已设置执行权限');
      }
    }
  } catch (error) {
    console.error('❌ 构建失败:', error);
    process.exit(1);
  }
}

build();